/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.common.security.config

import com.gitee.minimalismstyle.fresh.common.security.intercept.DynamicFilterSecurityInterceptor
import org.springframework.boot.autoconfigure.AutoConfigureBefore
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
import org.springframework.cloud.commons.security.AccessTokenContextRelay
import org.springframework.cloud.commons.security.ResourceServerTokenRelayAutoConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.access.AccessDecisionVoter
import org.springframework.security.access.vote.AffirmativeBased
import org.springframework.security.oauth2.client.OAuth2ClientContext
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler
import org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource
import org.springframework.security.web.access.expression.WebExpressionVoter

/**
 * 权限统一配置
 * @author maoxiaodong
 */
@Configuration
@AutoConfigureBefore(ResourceServerTokenRelayAutoConfiguration.ResourceServerTokenRelayRegistrationAutoConfiguration::class)
class FreshSecurityConfig {

    @Bean
    fun accessTokenContextRelay(context: OAuth2ClientContext?): AccessTokenContextRelay? {
        return AccessTokenContextRelay(context)
    }
    @Bean
    fun getDynamicFilterSecurityInterceptor(): DynamicFilterSecurityInterceptor {
        val interceptor = DynamicFilterSecurityInterceptor()
        interceptor.securityMetadataSource = ExpressionBasedFilterInvocationSecurityMetadataSource(linkedMapOf(), OAuth2WebSecurityExpressionHandler())

        //配置Voter决策
        val expressionVoter = WebExpressionVoter()
        expressionVoter.setExpressionHandler(OAuth2WebSecurityExpressionHandler())
        val decisionVoters: List<AccessDecisionVoter<*>> = listOf(
                expressionVoter
        )
        //设置认证决策管理器
        interceptor.accessDecisionManager = AffirmativeBased(decisionVoters)
        return interceptor
    }

}